﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Admin;
using SmartSiteManagementSystem.Models.DTO;
using SmartSiteManagementSystem.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{
    [TypeFilter(typeof(LoginAuthorizeAttribute))]
    public class AdminMenuController : AdminBaseControllers
    {
        private readonly ILogger<AdminMenuController> _logger;
        //注入后台服务
        private readonly IAdminService _adminService;
        public AdminMenuController(IAdminService adminService, ILogger<AdminMenuController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
        }

        string[] stringSeparators = new string[] { "|&&|" };


        /// <summary>
        /// 后台菜单管理
        /// </summary>
        public ViewResult Index()
        {
            return View();
        }
        /// <summary>
        /// 左侧树
        /// </summary>
        /// <returns></returns>
        public ViewResult Left()
        {
            return View();
        }
        /// <summary>
        /// 获取树数据
        /// </summary>
        /// <param name="pmenuId"></param>
        /// <returns></returns>
        public JsonResult GetMenuList(int pmenuId = 1)
        {
            IList<AdminMenuInfo> menulist = _adminService.GetAllMenuInfoList();
            IEnumerable<AdminMenuInfo> rootlist = menulist.Where(m => m.ParentId == 0);
            List<TreeModel> tree = new List<TreeModel>();
            foreach (var item in rootlist)
            {
                TreeModel node = new TreeModel();
                node.id = item.AdminMenuId;
                node.text = item.MenuName;
                //node.Data = item;
                if (item.IsParent)
                {
                    node.children = GetTreeChild(menulist, item);
                }
                node.url = "Edit?action=edit&parentId=0&adminMenuId=" + node.id;
                tree.Add(node);
            }
            //return Json(tree, JsonRequestBehavior.AllowGet);
            return Json(tree);
        }

        /// <summary>
        /// 递归加载树
        /// </summary>
        /// <param name="menulist"></param>
        /// <param name="curNode"></param>
        /// <returns></returns>
        private List<TreeModel> GetTreeChild(IList<AdminMenuInfo> menulist, AdminMenuInfo curNode)
        {
            IEnumerable<AdminMenuInfo> childlist = menulist.Where(m => m.ParentId == curNode.AdminMenuId);
            List<TreeModel> tree = new List<TreeModel>();
            foreach (var item in childlist)
            {
                TreeModel node = new TreeModel();
                node.id = item.AdminMenuId;
                node.text = item.MenuName;
               
                if (item.IsParent)
                {
                    node.children = GetTreeChild(menulist, item);
                }
                tree.Add(node);
                node.url = "Edit?action=edit&parentId=" + curNode.AdminMenuId + "&adminMenuId=" + node.id;
            }
            return tree;
        }
        /// <summary>
        /// 编辑界面
        /// </summary>
        /// <param name="action"></param>
        /// <param name="adminMenuId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ViewResult Edit(string action, int adminMenuId, int parentId = 0)
        {
            action = action.ToLower();
            if (adminMenuId == 0)
            {
                action = "add";
            }
            AdminMenuInfo parentMenuObj = new AdminMenuInfo();
            AdminMenuInfo MenuObj = new AdminMenuInfo();
            ViewBag.menuType = 0;
            if (action == "add")
            {
                if (parentId > 0)
                {
                    AdminMenuInfo parentMAdminMenuObj = _adminService.GetAdminMenuInfoById(parentId);
                    MenuObj.ParentName = parentMAdminMenuObj.MenuName;
                }
                else
                    MenuObj.ParentName = "根节点";

                MenuObj.ParentId = parentId;
            }
            else if (action == "edit")
            {
                MenuObj = _adminService.GetAdminMenuInfoById(adminMenuId);
                parentMenuObj = _adminService.GetAdminMenuInfoById(MenuObj.ParentId);

                if (string.IsNullOrEmpty(MenuObj.ParentName))
                    MenuObj.ParentName = "根节点";

                //菜单关联的路径
                string RelevanceUrl = MenuObj.RelevanceUrl;
                if (RelevanceUrl != null && RelevanceUrl != "")
                {
                    if (RelevanceUrl.IndexOf("|&&|") >= 0)
                    {
                        //string[] stringSeparators = new string[] { "|&&|" };
                        string[] RelevanceUrlList = RelevanceUrl.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                        ViewBag.RelevanceUrlList = RelevanceUrlList;
                    }
                    else
                    {
                        ViewBag.RelevanceUrlList = RelevanceUrl;
                    }
                }
                Hashtable p = new Hashtable();
                p.Add("admin_menu_id", adminMenuId);
                MenuObj.TAdminPageBtnInfoList = _adminService.GetAdminPageBtnInfoListByParam(p, "sort_no asc", 0, 1000);
            }
            if (MenuObj.TAdminPageBtnInfoList == null)
            {
                MenuObj.TAdminPageBtnInfoList = new List<AdminPageBtnInfo>();
            }
            MenuObj.TAdminPageBtnInfoList.Add(new AdminPageBtnInfo() { BtnId = 0, BtnType = 0 });
            MenuObj.TAdminPageBtnInfoList.Add(new AdminPageBtnInfo() { BtnId = 0, BtnType = 1 });
            ViewBag.MenuObj = MenuObj;
            //QiJu.Common.Utils.LogHelper.TextLogger.Info(JsonConvert.SerializeObject(MenuObj));
            ViewBag.BtnList = MenuObj.TAdminPageBtnInfoList.Where(x => x.BtnType == 0);
            ViewBag.FilterList = MenuObj.TAdminPageBtnInfoList.Where(x => x.BtnType == 1);
            ViewBag.parentMenuObj = parentMenuObj;
            ViewBag.adminMenuId = adminMenuId;
            string sourceUrl = string.Empty;
            try
            {
                sourceUrl = HttpContext.Request.Headers["Referer"].FirstOrDefault();
            }
            catch { }

            ViewData["sourceUrl"] = sourceUrl;
            return View();
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        public JsonResult DoEdit(int adminMenuId, bool isParent, int parentId, string menuName, string MenuUrl, int sortOrder, string relevanceUrls, int[] btnId, string[] relList, string[] btnName, string[] btnClientId, int[] btnSortNo, int[] btnType, int stopFlag = 0, int showFlag = 0)
        {
            int result = 0;
            int resultMenuId = 0;
            ResultInfo resultObj = new ResultInfo();
            resultObj.IsSuccess = false;
            resultObj.Msg = "操作失败!";
            resultObj.Code = 200;

            AdminMenuInfo MenuObj = new AdminMenuInfo();
            MenuObj.ParentId = parentId;
            MenuObj.MenuName = menuName;
            MenuObj.Url = MenuUrl;
            MenuObj.IsParent = isParent;
            MenuObj.SortOrder = sortOrder;
            MenuObj.StopFlag = stopFlag == 1;
            MenuObj.ShowFlag = showFlag == 1;

            #region 判断url是否重复
            bool isExists = false;
            string repeatMenuName = "";
            if (!String.IsNullOrEmpty(MenuUrl))
            {
                Hashtable p = new Hashtable();
                p.Add("url", MenuUrl);
                p.Add("is_stop", 0);
                IList<AdminMenuInfo> list = _adminService.GetAdminMenuInfoListByParam(p, null, 0, 10);

                foreach (AdminMenuInfo item in list)
                {
                    if (item.AdminMenuId != adminMenuId)
                    {
                        isExists = true;
                        repeatMenuName = item.MenuName;
                        break;
                    }
                }
            }
            if (isExists)
            {
                resultObj.IsSuccess = false;
                resultObj.Msg = "修改失败，重复的url，重复的菜单为“" + repeatMenuName + "”！";
                return Json(resultObj);
            }
            #endregion

            #region//菜单关联的路径
            if (relevanceUrls != null && relevanceUrls != "")
            {
                if (relevanceUrls.IndexOf("|&&|") > 0)
                {

                    string relevanceUrlMenu = "";

                    string[] relevanceUrlArr = relevanceUrls.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < relevanceUrlArr.Length; i++)
                    {
                        string relevanceUrl = relevanceUrlArr[i].ToString();
                        if (relevanceUrl == "") continue;
                        if (relevanceUrlMenu.IndexOf(relevanceUrl) <= 0)
                        {
                            if (relevanceUrlMenu == "")
                            {
                                relevanceUrlMenu += relevanceUrl;
                            }
                            else
                            {
                                relevanceUrlMenu += "|&&|" + relevanceUrl;
                            }

                        }

                    }

                    MenuObj.RelevanceUrl = relevanceUrlMenu;
                }
                else
                {
                    MenuObj.RelevanceUrl = relevanceUrls;
                }


            }
            else
            {
                MenuObj.RelevanceUrl = "";
            }



            #endregion

            if (adminMenuId > 0)
            {//修改
                MenuObj.AdminMenuId = adminMenuId;
                bool flag = _adminService.UpdateAdminMenuInfo(MenuObj);
                flag = flag && _adminService.UpdateAdminPageBtnInfo(btnId, relList, btnName, btnClientId, btnSortNo, btnType, adminMenuId, CurrentAdminUser.UserName);
                if (flag)
                {

                    //HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { success = true, msg = "修改成功!" }));
                    resultObj.IsSuccess = true;
                    resultObj.Msg = "修改成功！";
                    return Json(resultObj);

                }
                else
                {
                    //HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { success = false, msg = "修改失败!" }));
                    resultObj.IsSuccess = false;
                    resultObj.Msg = "修改失败！";
                    return Json(resultObj);

                }

            }
            else
            {//添加
                resultMenuId = _adminService.InsertAdminMenuInfo(MenuObj);
               
                bool flag = resultMenuId > 0;
                //如果添加的节点是某节点的子节点，则更新其父节点的IsParent字段为true
                if (resultMenuId > 0 && parentId > 0)
                {
                    AdminMenuInfo parentMenuObj = _adminService.GetAdminMenuInfoById(parentId);
                    if (parentMenuObj.IsParent == false)
                    {
                        parentMenuObj.IsParent = true;
                        _adminService.UpdateAdminMenuInfo(parentMenuObj);
                    }
                }
                //更新关联的按钮，搜索条件等
                flag = flag && _adminService.UpdateAdminPageBtnInfo(btnId, relList, btnName, btnClientId, btnSortNo, btnType, resultMenuId, CurrentAdminUser.UserName);
                if (flag)
                {
                    //HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { success = true, msg = "添加成功!" }));
                    resultObj.IsSuccess = true;
                    resultObj.Msg = "添加成功！";
                    return Json(resultObj);

                }
                else
                {
                    // HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { success = false, msg = "添加失败!" }));

                    resultObj.IsSuccess = false;
                    resultObj.Msg = "添加失败！";
                    return Json(resultObj);


                }

            }

        }
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="adminMenuId"></param>
        /// <returns></returns>
        public JsonResult DoDelete(int adminMenuId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            AdminMenuInfo MenuObj = _adminService.GetAdminMenuInfoById(adminMenuId);
            if (_adminService.DeleteMenuAndRelData(adminMenuId))
            {
                result.IsSuccess = true;
                result.Msg = "删除成功!";
            }
            else
            {
                result.IsSuccess = false;
                result.Msg = "删除失败!";
            }
            return Json(result);
        }

    }
}
